package qq.android.wan.qq.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import qq.android.wan.qq.R;
import qq.android.wan.qq.entity.UserBean;
import qq.android.wan.qq.utils.Constant;

/**
 * Created by wxx on 2016/4/5.
 */
public class RegisteActivity extends Activity implements View.OnClickListener {
    private ImageView iv_center_password;
    private Button btn_cancle, btn_ok;
    private EditText et_account, et_password;
    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registe);
        initUI();
        initListener();
    }


    private void initUI() {
        iv_center_password = (ImageView) findViewById(R.id.iv_center_password);
        btn_cancle = (Button) findViewById(R.id.btn_cancle);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        et_password = (EditText) findViewById(R.id.et_password);
        et_account = (EditText) findViewById(R.id.et_account);
    }

    private void initListener() {
        iv_center_password.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
        btn_ok.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancle:
                finish();
                break;
            case R.id.btn_ok:
                clickRegiste();
                break;
            case R.id.iv_center_password:
                clickCenterPw();
                break;
        }
    }

    private void clickRegiste() {
        String st_password = et_password.getText().toString();
        if (st_password.trim().equals("")) {
            Toast.makeText(RegisteActivity.this, "密码不能为空",
                    Toast.LENGTH_SHORT).show();
            return;
        } else if (st_password.length() < 6) {
            Toast.makeText(RegisteActivity.this, "密码不能少于6位",
                    Toast.LENGTH_SHORT).show();
            return;
        }else{
            Pattern pattern1 = Pattern.compile("^\\w+$");
            Matcher matcher1 = pattern1.matcher(st_password);
            //数字、字母、下划线的正则表达式^\w+$
            if(!matcher1.find()){
                Toast.makeText(RegisteActivity.this, "密码包含非法字符",
                        Toast.LENGTH_SHORT).show();
                return;
            }
        }
        pd=new ProgressDialog(RegisteActivity.this);
        pd.setMessage("正在注册");
        pd.show();
        registeOnServer();
    }

    private void clickCenterPw() {
        if (et_password.getTag().equals("on")) {
            et_password.setTag("off");
            et_password.setInputType(InputType.TYPE_CLASS_TEXT);

        } else {
            et_password.setTag("on");
            et_password.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
        et_password.clearFocus();
    }
    private void registeOnServer(){
        AsyncHttpClient client=new AsyncHttpClient();
String url= Constant.INTENT_ADDRESS+"User_add";
        RequestParams params=new RequestParams();
        params.put("user.phone", et_account.getText().toString());
        params.put("user.password", et_password.getText().toString());
        client.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String result = new String(bytes);
                Log.e("test", "服务器返回的结果是:" + result);
                if (result.equals("false") || result == null || result.equals("")) {
                    Toast.makeText(RegisteActivity.this, "该号码已被注册", Toast.LENGTH_SHORT).show();
                    pd.dismiss();
                    return;
                }
                registeEM();
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Toast.makeText(RegisteActivity.this, "注册失败", Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        });
    }
    private void registeEM(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 调用sdk注册方法

                    EMChatManager.getInstance().createAccountOnServer(et_account.getText().toString(), et_password.getText().toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (final EaseMobException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pd.dismiss();
                            //注册失败
                            int errorCode = e.getErrorCode();
                            if (errorCode == EMError.NONETWORK_ERROR) {
                                Toast.makeText(getApplicationContext(), "网络异常，请检查网络！", Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.USER_ALREADY_EXISTS) {
                                Toast.makeText(getApplicationContext(), "用户已存在！", Toast.LENGTH_SHORT).show();
                            } else if (errorCode == EMError.UNAUTHORIZED) {
                                Toast.makeText(getApplicationContext(), "注册失败，无权限！", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getApplicationContext(), "注册失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
            }
        }).start();
    }
}
